<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        closable
      >
      </el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span
            >选择商品分类:
            <el-cascader
              v-model="selectedKeys"
              :options="cateList"
              :props="cascaderProps"
              @change="cateChange"
              clearable
            ></el-cascader>
          </span>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showAddFormDialog"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scoped">
                <el-tag
                  v-for="(item, index) in scoped.row.attr_vals"
                  :key="index"
                  type="primary"
                  closable
                  @close="handleDeleteVal(scoped.row,index)"
                  class="tags"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scoped.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showAddFormDialog"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scoped">
                <el-tag
                  v-for="(item, index) in scoped.row.attr_vals"
                  :key="index"
                  type="primary"
                  closable
                  @close="handleDeleteVal(scoped.row,index)"
                  class="tags"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scoped.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="titleText"
      :visible="isAddParamsVisible"
      width="50%"
      @close="addParamsDialogClose"
    >
      <el-form :model="formParams" ref="addParamsForm" label-width="100px">
        <el-form-item prop="attr_name" :label="titleText">
          <el-input v-model="formParams.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmParams" >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getCateList();
  },
  data() {
    return {
     
      formParams: {
        attr_name: "",
        attr_sel: "",
      },
      isAddParamsVisible: false,
      manyTableData: [],
      onlyTableData: [],

      activeName: "many",
      addCateForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0,
      },
      cascaderProps: {
        checkStrictly: true,
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      selectedKeys: [],
      cateList: [],
    };
  },
  methods: {
    showInput(row){
     row.inputVisible=true
     this.$nextTick(()=>{
       this.$refs.saveTagInput.focus()
     })
    },
     async handleInputConfirm(row) {
      if(row.inputValue===""){
        row.inputVisible = false;
        return
      }
      row.attr_vals.push(row.inputValue.trim());
     const {data:res} =await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
       attr_name:row.attr_name,
       attr_sel:row.attr_sel,
       attr_vals:row.attr_vals.join(" ")
     })
     if(res.meta.status===200){
       this.$message.success("添加成功")
       row.inputVisible = false;
      row.inputValue = "";
     }
     else{
       this.$message.error("添加失败")
       row.inputVisible = false;
      row.inputValue = "";
     }

      
    },
     async handleDeleteVal(row,index) {
      row.attr_vals.splice(index,1)
      const {data:res} =await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
       attr_name:row.attr_name,
       attr_sel:row.attr_sel,
       attr_vals:row.attr_vals.join(" ")
     })
     if(res.meta.status===200){
       this.$message.success("删除成功")
       row.inputVisible = false;
      row.inputValue = "";
     }
     else{
       this.$message.error("删除失败")
       row.inputVisible = false;
      row.inputValue = "";
     }
    },

    getCateList() {
      this.$http.get("categories").then((res) => {
        if (res.data.meta.status === 200) {
          this.cateList = res.data.data;
          console.log(this.cateList);
        } else {
          this.$message.error("获取失败");
        }
      });
    },
    cateChange() {
      this.getParams();
    },
    async getParams() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = [];
        this.manyTableData=[];
        this.onlyTableData=[]
        return;
      } else {
        // console.log(this.selectedKeys)

        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: this.activeName,
            },
          }
        );
        // if(res.meta.status!==200){
        //    this.$message.error("获取参数失败")

        //   }
        //    if(this.activeName==="many"){
        //     // console.log(this.activeName)
        //     console.log(this.activeName)

        //   this.manyTableData=res.data
        //   }
        //    else{
        //      this.onlyTableData=res.data
        //    }
        res.data.forEach((item) => {
          item.inputVisible=false;
          item.inputValue=''
          if (item.attr_vals === "") {
            item.attr_vals=[]
            return
          }
          item.attr_vals = item.attr_vals.split(" ");

        });
        if (res.meta.status === 200) {
          if (this.activeName === "many") {
            this.manyTableData = res.data;
          } else {
            this.onlyTableData = res.data;
          }
        } else {
          this.$message.error("请求参数失败");
        }
      }
    },
    handleTabClick(tab, event) {
      console.log(this.activeName);
      this.getParams();
    },
    addParamsDialogClose() {
      this.$refs.addParamsForm.resetFields();
      this.isAddParamsVisible = false;
    },
    showAddFormDialog() {
      if (this.activeName === "many") {
        this.formParams.attr_sel = "many";
        this.isAddParamsVisible = true;
      } else {
        this.formParams.attr_sel = "only";
        this.isAddParamsVisible = true;
      }
    },
    confirmParams() {
      console.log(this.formParams);
      this.$refs.addParamsForm.validate(async (valid) => {
        if (!valid) {
          return;
        } else {
          const { data: res } = await this.$http.post(
            `categories/${this.cateId}/attributes`,
            this.formParams
          );
          if (res.meta.status === 201) {
            this.$message.success("修改成功");

            this.isAddParamsVisible = false;
            this.getParams();
          } else {
            this.$message.error("修改失败");
            this.isAddParamsVisible = false;
            this.getParams();
          }
        }
      });
    },
  },

  computed: {
    titleText() {
      console.log(this.activeName);
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态参数";
      }
    },
    isBtnDisabled() {
      if (this.selectedKeys.length === 0) {
        return true;
      } else {
        return false;
      }
    },
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2];
      }
    },
  },
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0px;
}
.tags {
  margin-left: 20px;
}
.button-new-tag{
  margin-left: 10px;
}
.input-new-tag{
  margin-left:10px;
  width: 100px;
}
</style>